package com.oppodowngrader;

import android.content.Intent;
import android.net.VpnService;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private boolean isProxyRunning = false;
    private TextView statusText;
    private Button actionButton;
    private TextView logTextView;
    private ScrollView logScrollView;
    
    private ActivityResultLauncher<Intent> vpnLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    startProxyService();
                } else {
                    Toast.makeText(this, R.string.vpn_required, Toast.LENGTH_LONG).show();
                    LogUtils.e("用户拒绝VPN权限", null);
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        statusText = findViewById(R.id.statusText);
        actionButton = findViewById(R.id.actionButton);
        logTextView = findViewById(R.id.logTextView);
        logScrollView = findViewById(R.id.logScrollView);
        
        actionButton.setOnClickListener(v -> toggleProxyService());
        
        // 显示介绍性对话框
        if (savedInstanceState == null) {
            showIntroDialog();
        }
        
        // 初始化日志显示
        updateLogDisplay();
    }
    
    private void showIntroDialog() {
        new AlertDialog.Builder(this)
                .setTitle("欢迎使用OPPO耳机降级助手")
                .setMessage("本应用可帮助您将OPPO Enco Air4 Pro耳机降级到115.115.100版本。\n\n" +
                        "使用步骤：\n" +
                        "1. 点击"启动降级服务"按钮\n" +
                        "2. 允许VPN权限\n" +
                        "3. 打开HeyMelody应用\n" +
                        "4. 连接耳机并检查更新\n\n" +
                        "注意：固件降级可能存在风险，请谨慎操作。")
                .setPositiveButton("了解", null)
                .show();
    }

    private void toggleProxyService() {
        if (isProxyRunning) {
            stopProxyService();
        } else {
            prepareVpn();
        }
    }
    
    private void prepareVpn() {
        Intent vpnIntent = VpnService.prepare(this);
        if (vpnIntent != null) {
            LogUtils.d("请求VPN权限");
            vpnLauncher.launch(vpnIntent);
        } else {
            startProxyService();
        }
    }
    
    private void startProxyService() {
        LogUtils.event("启动降级服务");
        Intent serviceIntent = new Intent(this, ProxyVpnService.class);
        startService(serviceIntent);
        isProxyRunning = true;
        updateUI();
        Toast.makeText(this, R.string.service_started, Toast.LENGTH_LONG).show();
    }
    
    private void stopProxyService() {
        LogUtils.event("停止降级服务");
        Intent serviceIntent = new Intent(this, ProxyVpnService.class);
        stopService(serviceIntent);
        isProxyRunning = false;
        updateUI();
        Toast.makeText(this, R.string.service_stopped_toast, Toast.LENGTH_SHORT).show();
    }
    
    private void updateUI() {
        if (isProxyRunning) {
            statusText.setText(R.string.service_running);
            actionButton.setText(R.string.stop_proxy);
        } else {
            statusText.setText(R.string.service_stopped);
            actionButton.setText(R.string.start_proxy);
        }
        updateLogDisplay();
    }
    
    private void updateLogDisplay() {
        StringBuilder logBuilder = new StringBuilder();
        for (LogUtils.LogEntry entry : LogUtils.getLogEntries()) {
            logBuilder.append(entry.toString()).append("\n");
        }
        
        logTextView.setText(logBuilder.toString());
        logScrollView.post(() -> logScrollView.fullScroll(View.FOCUS_DOWN));
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        updateLogDisplay();
    }
    
    @Override
    protected void onDestroy() {
        if (isProxyRunning) {
            stopProxyService();
        }
        super.onDestroy();
    }
}